<template>
  <div class="app-container calendar-list-container">
    <div class="filter-container">
      <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item" placeholder="名称" v-model="listQuery.title">
      </el-input>

      <el-select clearable class="filter-item" style="width: 130px" v-model="listQuery.status" placeholder="状态">
        <el-option v-for="item in  statusOptions" :key="item.key" :label="item.label" :value="item.code">
        </el-option>
      </el-select>

      <el-button class="filter-item" type="primary" v-waves icon="el-icon-search" @click="handleFilter">搜索</el-button>
      <el-button class="filter-item" style="margin-left: 10px;" @click="handleCreate(undefined)" type="primary" icon="el-icon-edit">添加</el-button>
    </div>

    <tree-table :data="list" :expandAll="true" border>
      <el-table-column align="center" label="序号" width="65">
        <template slot-scope="scope">
          <span>{{scope.row.id}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="名称">
        <template slot-scope="scope">
          <span>{{scope.row.name}}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="模块">
        <template slot-scope="scope">
          <span>{{scope.row.module}}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="路由" >
        <template slot-scope="scope">
          <span>{{scope.row.route}}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="权限" >
        <template slot-scope="scope">
          <span>{{scope.row.rule}}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="排序" >
        <template slot-scope="scope">
          <span>{{scope.row.sort}}</span>
        </template>
      </el-table-column>

      <el-table-column width="150" class-name="status-col" label="状态" >
        <template slot-scope="scope">
          <el-tag :type="scope.row.status | statusTagFilter">{{scope.row.status | statusTextFilter}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="left" label="操作" width="240px" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
          <template v-if="scope.row.status===1">
            <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
            <el-button v-if="scope.row._level < 3" type="success" size="mini" @click="handleCreate(scope.row.id)">添加</el-button>
          </template>
          <el-button v-else size="mini" type="warning" @click="handleDelete(scope.row)">恢复</el-button>
        </template>
      </el-table-column>
    </tree-table>

    <el-dialog :title="dialogTitleMap[dialogStatus]" :visible.sync="dialogFormVisible" custom-class="group-dlg">
      <el-form :rules="rules" ref="dataForm" :model="temp" label-position="right" label-width="100px" style='margin-left:50px;margin-right: 50px;'>
        <el-form-item label="名称" prop="name">
          <el-input v-model="temp.name"></el-input>
        </el-form-item>

        <el-form-item label="对应模块" prop="module" >
          <el-select class="filter-item" v-model="temp.module" placeholder="请选择所属模块">
            <el-option v-for="item in  moduleOptions" :key="item.id" :label="item.title" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="路由" prop="route">
          <el-input v-model="temp.route"></el-input>
        </el-form-item>

        <el-form-item label="权限" prop="rule">
          <el-input v-model="temp.rule"></el-input>
        </el-form-item>

        <el-form-item label="排序" prop="sort">
          <el-input v-model.number="temp.sort"></el-input>
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-select class="filter-item" v-model="temp.status" placeholder="请选择默认状态">
            <el-option v-for="item in  statusOptions" :key="item.code" :label="item.label" :value="item.code">
            </el-option>
          </el-select>
        </el-form-item>

      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">确认</el-button>
        <el-button v-else type="primary" @click="updateData">确认</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  // 分为集团组管理，更为方便一点
  // 二级管理
  import { fetchList, saveRule, updateRule, deleteRule } from '@/api/rule'
  import treeTable from '@/components/TreeTable'
  import waves from '@/directive/waves' // 水波纹指令

  const statusOptions = [
    { key: 'success', label: '正常', code: 1 },
    { key: 'warning', label: '异常', code: 0 },
    { key: 'danger', label: '删除', code: -1 }
  ]
  const statusKeyValue = statusOptions.reduce((acc, cur) => {
    acc[cur.code] = { tag: cur.key, txt: cur.label }
    return acc
  }, {})

  export default {
    name: 'rule',
    components: { treeTable },
    directives: {
      waves
    },
    data() {
      return {
        tableKey: 0,
        list: [],
        total: 0,
        listLoading: true,
        listQuery: {
          page: 1,
          limit: 20,
          title: undefined,
          status: undefined
        },
        moduleOptions: [
          { id: 'manage', title: '后台管理' }
        ],
        statusOptions,
        temp: {
          id: undefined,
          name: '',
          module: 'manage',
          route: undefined,
          rule: undefined,
          sort: undefined,
          status: 1
        },
        dialogFormVisible: false,
        dialogStatus: '',
        dialogTitleMap: {
          update: '编辑',
          create: '创建'
        },
        rules: {
          name: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
          module: [{ required: true, message: '权限不能为空', trigger: 'change' }]
        }
      }
    },
    filters: {
      statusTagFilter(status) {
        return statusKeyValue[status].tag
      },
      statusTextFilter(status) {
        return statusKeyValue[status].txt
      }
    },
    created() {
      this.getList()
    },
    methods: {
      getList() {
        this.listLoading = true
        const $vm = this
        this.axios.all([fetchList()]).then(this.axios.spread(function(list, create) {
          $vm.companyOptions = create
          $vm.list = list.items
          $vm.total = list.total
          $vm.listLoading = false
        }))
      },
      companyFilter(company_id) {
        if (!company_id) return '超级管理员'
        const list = this.companyOptions
        if (list === null) return
        for (let i = 0, len = list.length; i < len; i++) {
          if (list[i].id === company_id) return list[i].title
        }
      },
      handleFilter() {
        this.listQuery.page = 1
        this.getList()
      },
      resetTemp(pid) {
        this.temp = {
          id: undefined,
          name: '',
          module: 'manage',
          route: undefined,
          rule: undefined,
          sort: undefined,
          pid: pid,
          status: 1
        }
      },
      handleCreate(pid) {
        this.resetTemp(pid)
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      createData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            saveRule(this.temp).then((data) => {
              this.temp.id = data.id
              if (this.temp.pid === 0) {
                this.list.push(this.temp)
              } else {
                this.getList()
              }

              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '创建成功',
                type: 'success',
                duration: 2000
              })
            })
          }
        })
      },
      handleUpdate(row) {
        // copy obj
        this.temp = Object.assign({}, { id: row.id, module: row.module, name: row.name, pid: row.pid, route: row.route, rule: row.rule, sort: row.sort, status: row.status })
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      updateData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const tempData = Object.assign({}, this.temp)
            updateRule(tempData).then(() => {
              // 跟新树，如何处理节点，参考文档
              this.getList()
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 2000
              })
            })
          }
        })
      },
      handleDelete(row) {
        const status = row.status === 1
        deleteRule(row.id, status).then(() => {
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
          row.status = status ? -1 : 1
        })
      }
    }
  }
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
  .form-row{
    /*display: table;*/
    position: relative;
  }
  .form-row:after {
    clear: both;
  }
  .form-row:after, .form-row:before {
    display: table;
    content: "";
  }
</style>
<style rel="stylesheet/scss" lang="scss">
  .group-dlg {
    .el-dialog__body {
      padding-top: 5px;
    }
  }
</style>